package pt.ipl.isel.deetc.leic.pdm.g12.yamba;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class UserInfoActivity extends Activity implements ServiceConnection{
	private Intent intent = null;
	private Messenger userService;
	TextView name, messages, subscriptions, subscribers;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.userinfo);
		
		name = (TextView) findViewById(R.id.username);
		messages = (TextView) findViewById(R.id.nStatusMessages);
		subscriptions = (TextView) findViewById(R.id.nSubscriptions);
		subscribers = (TextView) findViewById(R.id.nSubscribers);
	}
	
	private Messenger callback = new Messenger(new Handler(){
		public void handleMessage(Message msg) {

			msg.getData().setClassLoader(UserInfo.class.getClassLoader()); 
			UserInfo user = msg.getData().getParcelable("UserInfo");
			
			name.setText(user.getScreenName());
			messages.setText(R.string.nMessagesText);
			messages.append(""+user.getStatus());
			subscriptions.setText(R.string.nSubscriptionText);
			subscriptions.append(""+user.getSubscriptions());
			subscribers.setText(R.string.nSubscribersText);
			subscribers.append(""+user.getSubscribers());
			
			name.setCompoundDrawables(user.getProfilePicture(), null, null, null);			
		};
	});
	
	private void getInfo(){
		if(userService == null)
			return;
		
		try{
			Log.i("PDM", "UserInfoActivity getInfo");
			Message m = Message.obtain(null, UserInfoPullService.USER_INFO, 0, 0, null);
			m.replyTo = callback;
			userService.send(m);
		}catch(RemoteException e){
			Toast.makeText(this, R.string.remote_error, Toast.LENGTH_LONG);
			Log.e("PDM", "Error @ UserInfoActivity.getInfo()", e);
		}
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		Log.i("PDM", "UserInfoActivity onStart");
		if(intent == null)
			intent = new Intent(this, UserInfoPullService.class);
		
		bindService(intent, this, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Log.i("PDM", "UserInfoActivity onResume");
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		if(userService != null)
			unbindService(this);
	}

	public void onServiceConnected(ComponentName name, IBinder service) {
		userService = new Messenger(service);
		Log.i("PDM", "UserInfoActivity onServiceConnected");
		getInfo();
	}

	public void onServiceDisconnected(ComponentName name) {
		userService = null;
		Log.i("PDM", "UserInfoActivity onServiceDisconnected");
	}
}
